//
//  XBShareManager.m
//  XBShare
//
//  Created by admin on 2018/5/14.
//  Copyright © 2018年 肖世恒. All rights reserved.
//

#import "XBShareManager.h"
#import "XBShareQQTIMView.h"
#import "QQApiInterface.h"
#import "WXApi.h"
#import "WXApiRequestHandler.h"
#import "WeiboSDK.h"

@interface XBShareManager()<QQApiInterfaceDelegate,WXApiDelegate,WeiboSDKDelegate,XBShareQQTIMViewDelegate>

@property (nonatomic, copy) XBSocialRequestCompletionHandler shareCompletionBlock;

@property (nonatomic ,strong) XBShareQQTIMViewModel *sharModel;//

@end

@implementation XBShareManager

+ (XBShareManager *)defaultManager{
    
    static XBShareManager * s_instance_dj_singleton = nil ;
    if (s_instance_dj_singleton == nil) {
        s_instance_dj_singleton = [[XBShareManager alloc] init];
    }
    return s_instance_dj_singleton;
}

- (void)selectType:(NSInteger)type{
    
    if(self.sharModel.type ==1){
        [self openQQJoinGroupNumWithplatformType:type groupNum:self.sharModel.groupNum groupKey:self.sharModel.groupKey completion:self.sharModel.completion];
    }else if(self.sharModel.type ==2){
        [self openQQChatWith:type QQNum:self.sharModel.qqNum completion:self.sharModel.completion];
    }else{
        XBSocialPlatformType Ptype;
        if((XBSocialPlatformType)type == XBSocialPlatformType_QQ){
            if( self.sharModel.isQZ){
                Ptype = XBSocialPlatformType_Qzone;
            }else{
                Ptype = XBSocialPlatformType_QQ;
            }
        }else{
            if( self.sharModel.isQZ){
                Ptype = XBSocialPlatformType_TimQZ;
            }else{
                Ptype = XBSocialPlatformType_Tim;
            }
        }
        [self shareToPlatform:Ptype messageObject:self.sharModel.messageObject completion:self.sharModel.completion];
    }
}

- (BOOL)handleOpenURL:(NSURL *)url {
    //是 这 三种 分享 才返回 yes 其他不做处理
    /*        host                     UIApplicationOpenURLOptionsSourceApplicationKey
     QQ登录    qzapp                    com.tencent.mqq
     QQ分享    response_from_qq         com.tencent.mqq
     QQ支付    qzapp
     新浪分享   response                 com.sina.weibo
     新浪分享   response                 com.sina.weibo
     微信分享   platformId=wechat        com.tencent.xin
     微信支付   pay                      com.tencent.xin
     支付宝支付   safepay
     支付宝授权   platformapi
     出了这种 是 没办法区分的 友盟 都不能做到
     */
    if ([url.host isEqualToString:@"response"]) {
        
        return [WeiboSDK handleOpenURL:url delegate:self];
        
    }else if ([url.host isEqualToString: @"platformId=wechat"]){
        
        return [WXApi handleOpenURL:url delegate:self];
        
    }else if ([url.host isEqualToString:@"response_from_qq"]){
        
        return [QQApiInterface handleOpenURL:url delegate:self];
    }
    else{
        return NO;
    }
}

/**
 给出 QQ 还是 TIM   自动转换 如果给类型8  返回也是 8
 QQSDK 提供的 垃圾了 自己写

 @param platformType 传入类型
 @return QQ 或者 TIM 或者3  QQ没有安装 -1 TIM没有安装 -2 其他是 -3
 */

/**
 给出 QQ 还是 TIM 还是两者都包含的2

 @param platformType 给出原始类型
 @param methodType 调用者  包括 分享3 加群1 临时会话2
 2 是单纯的加群1 临时会话2 时返回的
 3 是分享返回的
 @return  QQ 或者 TIM 或者2 3   QQ没有安装 -1 TIM没有安装 -2 都没有安装 -3 类型错误 -4
 */
- (NSInteger)perhapsQQTIM:(XBSocialPlatformType)platformType MethodType:(NSInteger)methodType{
    
    if(!(platformType == XBSocialPlatformType_QQ  || platformType == XBSocialPlatformType_Qzone ||
         platformType == XBSocialPlatformType_Tim || platformType == XBSocialPlatformType_TimQZ ||
         platformType == XBSocialPlatformTypeQQAndTIM)){
        return -4;
    }else if((platformType == XBSocialPlatformType_QQ ||
              platformType == XBSocialPlatformType_Qzone )
             && methodType == 3
             && ![[XBOAuth defaultManager] isInstall:XBSocialPlatformType_QQ]
             && [[XBOAuth defaultManager] isInstall:XBSocialPlatformType_Tim]){
        //在类型  4 或者 5 时 判断QQ没有安装 并且TIM 安装了 转换 成 TIM
        return ShareDestTypeTIM;
    }else if ((platformType == XBSocialPlatformType_Tim ||
               platformType == XBSocialPlatformType_TimQZ )
              && methodType == 3
              && ![[XBOAuth defaultManager] isInstall:XBSocialPlatformType_Tim]
              && [[XBOAuth defaultManager] isInstall:XBSocialPlatformType_QQ]){
        //在类型  6 或者 7 时 判断TIM没有安装 并且QQ 安装了 转换 成 QQ
        return ShareDestTypeQQ;
    }else if (![[XBOAuth defaultManager] isInstall:XBSocialPlatformType_QQ] &&
              ![[XBOAuth defaultManager] isInstall:XBSocialPlatformType_Tim]){
        //QQ 和 TIM 都没有安装时
        if(platformType == XBSocialPlatformTypeQQAndTIM){
            return -3;
        }else{
            return  platformType == XBSocialPlatformType_QQ || platformType == XBSocialPlatformType_Qzone ? -1 : -2;
        }
    }else if(platformType == XBSocialPlatformTypeQQAndTIM ){
        if(methodType == 3){
            return 3;
        }else{
            // methodType == 1 or 2
            return 2;
        }
    }else{
        //都安装
        return  platformType == XBSocialPlatformType_QQ || platformType == XBSocialPlatformType_Qzone ? ShareDestTypeQQ:ShareDestTypeTIM;
    }
}
- (NSError *)getQQTIMErerr:(NSInteger)type{
    
    //QQ没有安装 -1 TIM没有安装 -2 都没有安装 -3 类型错误 -4
    NSString *errorStr;
    if(type == -1){
        errorStr = @"QQ未安装";
    }else if (type == -2){
        errorStr = @"TIM未安装";
    }else if(type == -3){
        errorStr = @"QQ或者TIM未安装";
    }else{
        errorStr = @"输入类型错误";
    }
    
    NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
    NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
    
    return error;
}

- (void)openQQJoinGroupNumWithplatformType:(XBSocialPlatformType)platformType  groupNum:(NSString *)groupNum groupKey:(NSString *)groupKey  completion:(XBSocialRequestCompletionHandler)completion{
    
    NSInteger type = [self perhapsQQTIM:platformType MethodType:1];
    if(type < 0){
        completion(nil,[self getQQTIMErerr:type]);
    }else if(type == 2){
        
        self.sharModel = [XBShareQQTIMViewModel setModelGroupNum:groupNum groupKey:groupKey completion:completion];
        //经过选择 最终决定 类型
        [[XBShareQQTIMView defaultManager] showXBShareQQTIMView:self];
        
    }else{
        QQApiJoinGroupObject *joinGroupObject = [QQApiJoinGroupObject objectWithGroupInfo:groupNum key:groupKey];
        joinGroupObject.shareDestType = (ShareDestType)type;
        
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:joinGroupObject];
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        NSString *errorStr = [self handleSendResult:sent];
        if(errorStr.length > 0){
            
            NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
            NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
            completion(nil,error);
        }
    }
}
- (void)openQQChatWith:(XBSocialPlatformType)platformType QQNum:(NSString *)qqNum completion:(XBSocialRequestCompletionHandler)completion{
    
    NSInteger type = [self perhapsQQTIM:platformType MethodType:2];
    if(type < 0){
        completion(nil,[self getQQTIMErerr:type]);
    }else if(type == 2){
        
        self.sharModel = [XBShareQQTIMViewModel setModelQQNum:qqNum completion:completion];
        //经过选择 最终决定 类型
        [[XBShareQQTIMView defaultManager] showXBShareQQTIMView:self];
    }else{
        QQApiWPAObject *wpaObj = [QQApiWPAObject objectWithUin:qqNum];
        wpaObj.shareDestType = (ShareDestType)type;
        
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:wpaObj];
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        NSString *errorStr = [self handleSendResult:sent];
        if(errorStr.length > 0){
            
            NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
            NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
            completion(nil,error);
        }
    }

}
- (void)openWXChatWithJumpName:(NSString *)name  extMsg:(NSString *)extMsg completion:(XBSocialRequestCompletionHandler)completion{
    
    JumpToBizProfileReq *req = [[JumpToBizProfileReq alloc]init];
    
    req.username = name;
    req.extMsg = extMsg;
    req.profileType =  WXBizProfileType_Normal ;//跳转的公众号类型 WXBizProfileType
    
    BOOL error = [WXApi sendReq:req];
    
    //成功返回YES，失败返回NO。
    if(!error){
        NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"微信跳转公众号失败" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
        completion(nil,error);
    }
    
    
}
- (void)openWXChatWithUrl:(NSString *)url completion:(XBSocialRequestCompletionHandler)completion{
    
    OpenWebviewReq *req = [[OpenWebviewReq alloc] init];
    req.url = url;
    BOOL error = [WXApi sendReq:req];
    
    //成功返回YES，失败返回NO。
    if(!error){
        NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"微信浏览失败" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
        completion(nil,error);
    }
}


- (void)openWXChatWithWXNum:(NSString *)wxNum completion:(XBSocialRequestCompletionHandler)completion{
    
    OpenTempSessionReq *req = [[OpenTempSessionReq alloc] init];
    req.username = wxNum;
    req.sessionFrom = @"ios";
    BOOL error = [WXApi sendReq:req];
    
    //成功返回YES，失败返回NO。
    if(!error){
        NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"微信聊天失败" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
        completion(nil,error);
    }
}



- (void)shareToPlatform:(XBSocialPlatformType)platformType
          messageObject:(XBSocialMessageObject *)messageObject
             completion:(XBSocialRequestCompletionHandler)completion{
    
    self.shareCompletionBlock = nil;
    self.shareCompletionBlock = completion;
    
    //先获取 缩略图
    NSData *dataImage = [NSData  dataWithContentsOfURL:[NSURL URLWithString:messageObject.previewURL.absoluteString]];
    
    if(platformType==1  ||  platformType==2 ||  platformType ==3 ){
        
    
        if([messageObject isMemberOfClass:[XBSocialMessageNewObject class]]){
            
            XBSocialMessageNewObject *object = (XBSocialMessageNewObject *)messageObject;
            
            BOOL error = [WXApiRequestHandler
                          sendLinkURL:object.webUrl.absoluteString    //url
                                     TagName:@"ios" //
                                       Title:object.title         //标题
                                 Description:object.descr  //描述
                                  ThumbImage: [UIImage imageWithData:dataImage]       //本地图片
                                     InScene:(enum WXScene)platformType - 1];   //目标场景
            //成功返回YES，失败返回NO。
            if(!error){
                NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"微信发送失败" forKey:NSLocalizedDescriptionKey];
                NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
                completion(nil,error);
            }
            
        }
        
    }else if(platformType == XBSocialPlatformType_QQ    ||
             platformType == XBSocialPlatformType_Qzone ||
             platformType == XBSocialPlatformType_Tim   ||
             platformType == XBSocialPlatformType_TimQZ ||
             platformType == XBSocialPlatformTypeQQAndTIM ||
             platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_QQ)    ||
             platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_Qzone) ||
             platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_Tim)   ||
             platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_TimQZ) ){
        
        XBSocialPlatformType sharetype;
        //这里 不可能 会出现  -3 的情况
        if(platformType == XBSocialPlatformType_QQ    ||
           platformType == XBSocialPlatformType_Qzone ||
           platformType == XBSocialPlatformType_Tim   ||
           platformType == XBSocialPlatformType_TimQZ ){
            sharetype = platformType;
        }else{
            sharetype = XBSocialPlatformTypeQQAndTIM;
        }
        NSInteger type = [self perhapsQQTIM:sharetype MethodType:3];
        if(type < 0){
            completion(nil,[self getQQTIMErerr:type]);
        }else if(type == 3){
            XBShareQQTIMViewModel *mode;
            if(platformType == XBSocialPlatformTypeQQAndTIM){
                NSLog(@"没有设置空间还是聊天类型");
                return;
            }else if(platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_Qzone) ||
               platformType == (XBSocialPlatformTypeQQAndTIM | XBSocialPlatformType_TimQZ) ){
                mode = [XBShareQQTIMViewModel setModelIsQZ:YES messageObject:messageObject completion:completion];
            }else{
                //
                mode = [XBShareQQTIMViewModel setModelIsQZ:NO messageObject:messageObject completion:completion];
            }
            self.sharModel = mode;
            //经过选择 最终决定 类型
            [[XBShareQQTIMView defaultManager] showXBShareQQTIMView:self];
        }else{
            if([messageObject isMemberOfClass:[XBSocialMessageNewObject class]]){
                
                XBSocialMessageNewObject *object = (XBSocialMessageNewObject *)messageObject;
                
                QQApiNewsObject* newObj = [QQApiNewsObject objectWithURL:object.webUrl title:object.title description:object.descr previewImageURL:object.previewURL];
                newObj.shareDestType = (ShareDestType)type;
                newObj.cflag = platformType==4||platformType==6 ?   kQQAPICtrlFlagQQShare:kQQAPICtrlFlagQZoneShareOnStart;
                
                SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:newObj];
                QQApiSendResultCode sent = [QQApiInterface sendReq:req];
                NSString *errorStr = [self handleSendResult:sent];
                if(errorStr.length > 0){
                    
                    NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey];
                    NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
                    completion(nil,error);
                }
            }
        }
        
    }else if(platformType == XBSocialPlatformType_Sina){
        
        if([messageObject isMemberOfClass:[XBSocialMessageNewObject class]]){
            
            XBSocialMessageNewObject *object = (XBSocialMessageNewObject *)messageObject;
        
            WBWebpageObject *webpage = [WBWebpageObject object];
            webpage.title = object.title;
            webpage.description = object.descr;
            webpage.webpageUrl = object.webUrl.absoluteString;
            webpage.thumbnailData =  dataImage;
            webpage.objectID = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
            
            WBMessageObject *message = [WBMessageObject message];
            message.mediaObject = webpage;
            
            WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
            BOOL error = [WeiboSDK sendRequest:request];
            //成功返回YES，失败返回NO。
            if(!error){
                NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"微博发送失败" forKey:NSLocalizedDescriptionKey];
                NSError *error = [NSError errorWithDomain:@"Domain" code:-1 userInfo:userInfo];
                completion(nil,error);
            }
        }

    }else{
        NSLog(@"撒也不是");
    }
    
}

- (NSString *)handleSendResult:(QQApiSendResultCode)sendResult
{
    
    if(sendResult == EQQAPIAPPNOTREGISTED){
        return @"App未注册";
    }else if (sendResult == EQQAPIMESSAGECONTENTINVALID||
              sendResult == EQQAPIMESSAGECONTENTNULL ||
              sendResult == EQQAPIMESSAGETYPEINVALID){
        return @"发送参数错误";
    }else if (sendResult == EQQAPIQQNOTINSTALLED){
        return @"未安装QQ";
    }else if (sendResult == EQQAPITIMNOTINSTALLED){
        return @"未安装TIM";
    }else if (sendResult == EQQAPIQQNOTSUPPORTAPI || sendResult == EQQAPITIMNOTSUPPORTAPI){
        return  @"API接口不支持";
    }else if (sendResult == EQQAPISENDFAILD){
        return  @"发送失败";
    }else if (sendResult == EQQAPIVERSIONNEEDUPDATE){
        return @"当前QQ版本太低，需要更新";
    }else if (sendResult == ETIMAPIVERSIONNEEDUPDATE){
        return @"当前TIM版本太低，需要更新";
    }else{
        return @"";
    }
}

#pragma  mark QQQQApiInterfaceDelegate
- (void)isOnlineResponse:(NSDictionary *)response{
    
}
#pragma  ++++++++QQQQApiInterfaceDelegate 微信WXApiDelegate 协议 通用 onReq ， onResp ++++++
// 从QQ或者微信启动
- (void)onReq:(id)req {
    if([req isKindOfClass:[BaseReq class]]){
        //有需要就用吧
        if ([req isKindOfClass:[GetMessageFromWXReq class]]) {
            //微信终端向第三方程序请求提供内容的消息结构体
        } else if ([req isKindOfClass:[ShowMessageFromWXReq class]]) {
            //微信终端向第三方程序发送的要求第三方程序处理的多媒体内容
        } else if ([req isKindOfClass:[LaunchFromWXReq class]]) {
            //微信终端打开第三方程序携带的消息结构体
        }else{
            NSLog(@"XBShare%@",req);
        }
    }else if([req isKindOfClass:[QQBaseReq class]]){
        NSLog(@"XBShare%@",req);
    }else{
        NSLog(@"撒也不是");
    }
}
//QQ或者微信发送媒体消息结果
- (void)onResp:(id)resp {
    
    if([resp isKindOfClass:[BaseResp class]]){
        BaseResp *baseResp = (BaseResp *)resp;
        //写怎么多返回结果 只是为了弄明白
        if ([baseResp isKindOfClass:[SendMessageToWXResp class]]) {
        
            if(self.shareCompletionBlock){
                //  分享结果 处理
                if (baseResp.errCode == WXSuccess) {
                    self.shareCompletionBlock(@{@"message":@"分享成功",@"Code":[NSString stringWithFormat:@"%i",baseResp.errCode]}, nil);
                }else {
                    //分享失败
                    NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"分享失败" forKey:NSLocalizedDescriptionKey];
                    NSError *error = [NSError errorWithDomain:@"Domain" code:baseResp.errCode userInfo:userInfo];
                    self.shareCompletionBlock(nil, error);
                }
            }
        } else if ([baseResp isKindOfClass:[SendAuthResp class]]) {
            //微信处理完第三方程序的认证和权限申请后向第三方程序回送的处理结果。
        } else if ([baseResp isKindOfClass:[AddCardToWXCardPackageResp class]]) {
            //微信返回第三方添加卡券结果
        } else if ([baseResp isKindOfClass:[WXChooseCardResp class]]) {
            //微信返回第三方请求选择卡券结果
        }else if ([baseResp isKindOfClass:[WXChooseInvoiceResp class]]){
            //微信返回第三方请求选择发票结果
        }else if ([baseResp isKindOfClass:[WXSubscribeMsgResp class]]){
            //微信返回第三方请求订阅结果
        }else{
            NSLog(@"XBShare%@",resp);
        }
    }else if([resp isKindOfClass:[QQBaseResp class]]){
        QQBaseResp *qqBaseResp = (QQBaseResp *)resp;
        if ([qqBaseResp isKindOfClass:[SendMessageToQQResp class]]) {
            if(self.shareCompletionBlock){
                if (qqBaseResp.type ==ESENDMESSAGETOQQRESPTYPE && [qqBaseResp.result integerValue] == 0) {
                    //分享成功
                   self.shareCompletionBlock(@{@"message":@"分享成功",@"Code":qqBaseResp.result}, nil);
                }
                else{
                    //分享失败
                    NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"分享失败" forKey:NSLocalizedDescriptionKey];
                    NSError *error = [NSError errorWithDomain:@"Domain" code:[qqBaseResp.result integerValue] userInfo:userInfo];
                    self.shareCompletionBlock(nil, error);
                }
            }
        }
        else{
            NSLog(@"XBShare%@",resp);
        }
        
    }else{
        NSLog(@"XBShare撒也不是");
    }
}
#pragma mark -- WeiboSDKDelegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        if(self.shareCompletionBlock){
            if (response.statusCode == WeiboSDKResponseStatusCodeSuccess ) {
                //分享成功
                self.shareCompletionBlock(@{@"message":@"分享成功",@"Code":[NSString stringWithFormat:@"%li",(long)response.statusCode]}, nil);
            }
            else{
                //分享失败
                NSDictionary *userInfo =  [NSDictionary dictionaryWithObject:@"分享失败" forKey:NSLocalizedDescriptionKey];
                NSError *error = [NSError errorWithDomain:@"Domain" code:response.statusCode userInfo:userInfo];
                self.shareCompletionBlock(nil, error);
            }
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSLog(@"认证结果,\n这个SDK 没法在handleOpenURL方法区分授权还是分享 \n 要么那这个SDK把授权做了，要么拿这个SDK源码来做");

    }
}


@end
